<?php

namespace App\Services;

use App\Models\Group;
use Excel;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
use Illuminate\Support\Facades\Log;

/**
 * Class HelpService
 * @package App\Services
 *
 * 公用方法集合类
 * 注意: 定义时直接定义public static function
 * <code>
 *   public function some_public_method($a)
 * </code>
 * 此类已在 config/app.php 中aliases数组中注册
 * 代码中的调用方法:
 * <code>
 *   ...
 *   Helper::some_public_method($a);
 * </code>
 */
class HelpService
{

    /**
     * 随机生成数字+字母组合的字符串
     * @param $len
     * @return array|string
     */
    public static function createRandomStr($len)
    {
        $str = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
        shuffle($str);
        $str = implode('', array_slice($str, 0, $len));
        return $str;
    }

    /**
     * <h2>Helper::get_filter</h2>
     * @param s|string $key
     * @param $value
     * @param bool $needArray
     * @return array 返回过滤信息数组, 如无过滤信息则返回空数组
     * <code>
     * $filter = Helper::get_filter();
     * </code>
     */
    public static function get_filter($key = 'f', $value = null, $needArray = true)
    {
        // 前端传递的参数会把末尾的==给删除, 转码前必须加上。
        $raw = is_null($value) ? request($key, '') . '==' : $value;
        if (!empty($raw)) {
            if (strpos($raw, ' ') !== false) {
                $raw = str_replace(' ', '+', $raw);
            }
            $json_str = base64_decode($raw);
            return json_decode($json_str, $needArray);
        }
        return [];
    }

    /**
     * 编码转换
     * @param $string
     * @param bool $out_put
     * @return mixed|string
     */
    public static function transcoding($string, $out_put = true, $type = null)
    {
        $system = $type ? $type : substr(PHP_OS, 0, 3);
        if ($system === 'WIN') {
            if ($out_put) {
                return mb_convert_encoding($string, 'GBK', 'UTF-8');
            } else {
                return mb_convert_encoding($string, 'UTF-8', 'GBK');
            }
        }
        return $string;
    }

    /**
     * 递归删除文件夹
     * @param $path
     * @return bool
     */
    public static function deleteDir($path)
    {

        if (!is_dir($path)) {
            return false;
        }

        $fh = opendir($path);
        while (($row = readdir($fh)) !== false) {
            //过滤掉虚拟目录
            if ($row == '.' || $row == '..') {
                continue;
            }

            if (!is_dir($path . '/' . $row)) {
                unlink($path . '/' . $row);
            }
            self::deleteDir($path . '/' . $row);

        }
        closedir($fh);
        if (!rmdir($path)) {
            return false;
        }
        return true;
    }

    /**
     * 递归创建文件夹
     * @param $path
     * @return bool
     */
    public static function makeDir($path)
    {
        if (!is_dir($path)) {
            if (!self::makeDir(dirname($path))) {
                return false;
            }
            if (!mkdir($path, 0777)) {
                return false;
            }
        }
        return true;
    }

    public static function getFileContent($items, $dir, $default = [])
    {
        $result = [];
        if (is_array($items)) {
            foreach ($items as $item) {
                $file_name = storage_path($dir . $item . '.json');
                $result[$item] =
                    file_exists($file_name) ? json_decode(file_get_contents($file_name)) : $default;
            }
        } else {
            $file_name = storage_path($dir . $items . '.json');
            //如果传入参数所对应的json文件不存在，返回空字符串
            $result =
                file_exists($file_name) ? json_decode(file_get_contents($file_name)) : $default;
        }
        return $result;
    }

    public static function initEventSource()
    {
        array_map(function ($headerStr) {
            header($headerStr);
        }, [
            'content-type: text/event-stream',
            'cache-control: no-cache',
            'connection: keep-alive',
        ]);
        if (config('debug')) {
            header('Access-Control-Allow-Origin: http://localhost:8989');
            header('Access-Control-Allow-Credentials: true');
        }
    }

    public static function isMobile()
    {
        $userAgent = request()->header('user-agent');
        return str_contains($userAgent, ['Android', 'iPhone']);
    }

    public static function letterOperate($letter, $operate, $num)
    {
        $result = ord($letter);
        if ($operate === '+') {
            $result = $result + $num;
        } else if ($operate === '-') {
            $result = $result - $num;
        }
        $result = chr($result);
        return $result;
    }

    /**
     * 判断是否存在业务结构, 不存在就创建
     * @FunName: recursiveCreate
     * @Param: * @param int $i
     * @param $pid
     * @param $arr
     * @param $com_key
     * @return: 返回最后一次创建或者查询到的group_id
     */
    public static function recursiveCreate($i = 1, $pid, $arr, $com_key)
    {
        static $ids = [];
        if ($i < count($arr)) {
            $name = $arr[$i];
            $group_num = Group::where(['name' => $name, 'parent_id' => $pid, 'com_key' => $com_key])->get()->count();
            if ($group_num == 0 && $i < count($arr)) {
                $i++;
                $group = new Group();
                $group->name = $name;
                $group->children = [];
                $group->parent_id = $pid;
                $pGroup = Group::find($pid);
                if (!is_null($pGroup)) {
                    $group->com_key = $pGroup->com_key;
                    $group->save();
                    array_push($ids, $group->id);
                    //把创建好的id添加到传过来的group_id模型的children中
                    $pChild = $pGroup->children;
                    array_push($pChild, $group->id);
                    $pGroup->children = $pChild;
                    $pGroup->save();
                }
                self::recursiveCreate($i, $group->id, $arr, $com_key);
            } else {
                $i++;
                $group_ids = Group::where(['name' => $name, 'parent_id' => $pid, 'com_key' => $com_key])->get()->pluck('id')->all();
                array_push($ids, $group_ids[0]);
                self::recursiveCreate($i, $group_ids[0], $arr, $com_key);
            }
        }
        return $ids[count($ids) - 1];
    }

    /**
     * 先判断文件是否存在  存在的话 文件名继续+1, 保存文件
     * @FunName: fileName
     * @param $path
     * @param int $j
     * @param $prefix
     * @param string $type
     * @return string
     */
    public static function fileName($path, $j = 1, $prefix, $type = 'csv')
    {
        $fileName = $prefix . date('Y-m-d') . '_' . $j . '.' . $type;
        while ($j) {
            if (file_exists($path . $fileName)) {
                ++$j;
                $fileName = $prefix . date('Y-m-d') . '_' . $j . '.' . $type;
            } else {
                break;
            }
        }
        return $fileName;
    }

    // 随机生成一个不重复的数字给微信uin用
    public static function getRandUin()
    {
        $rand = mt_rand(time(), microtime(1) * 10000);
        return 't_' . $rand;
    }

    public static function makeMongoEmptyFilter($_field)
    {
        $query = <<<JSON
{"\$or":[{"$_field":{"\$in":[0,"",null]}},{"$_field":{"\$exists":false}}]}
JSON;
        $r = json_decode($query, 1);
        return [$r];
    }

    public static function fmtISODate($time = null)
    {
        return sprintf(
            "ISODate('%s')",
            strftime('%Y-%m-%d', $time ?? time())
        );
    }

    /**
     * 获取excel表数据
     */

    public static function getExcelInfo($filePath)
    {
        $res = [];
        Excel::load($filePath, function ($reader) use (&$res) {
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
        });
        $firstKey = array_pull($res, 0);
        $excel_content = array_map(function ($value) use ($firstKey) {
            $arr = array_combine($firstKey, $value);
            return $arr;
        }, $res);
        foreach ($excel_content as $key => $value) {
            $excel_content[$key]['index'] = $key + 1;
        }
        $arr = [
            'firstKey'=>$firstKey,
            'excelContent'=>$excel_content
        ];
        return $arr;
    }

    /**
     * 下载模板
     */
    public static function exportModel($path) {

        if (file_exists($path)) {
            $file_size = filesize($path);
            header("Content-type: application/octet-stream");
            header("Accept-Ranges: bytes");
            header("Accept-Length:".$file_size);
            header("Content-Disposition: attachment; filename=example.xlsx");
            $file_content = file_get_contents($path);
            echo $file_content;
        } else {
            echo '文件不存在';
        }
        exit;
    }

    /**
     * @param $stream
     * @param $level
     * @return mixed
     */
    static function  getLog($stream, $level) {
        $log = Log::getMonolog();
        $handler = new StreamHandler($stream, $level);
        $handler->setFormatter(new LineFormatter(null, null, true, true));
        $log->popHandler();
        $log->pushHandler($handler);
        return $log;
    }
}
